package com.basic.webframe;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;

import com.basic.common.FuncStatic;
import com.basic.webframe.HtmlBuilder;

public class VelocityPackage extends Directive {

	@Override
    public String getName() { return "package"; } //指定指令的名称

    @Override
    public int getType() { return BLOCK; } //指定指令类型为块指令

	@Override
	public boolean render(InternalContextAdapter context, Writer writer,
			Node node) throws IOException, ResourceNotFoundException,
			ParseErrorException, MethodInvocationException {
		int nodeCount = node.jjtGetNumChildren();
		String viewPath = FuncStatic.trim(node.jjtGetChild(0).getFirstToken().image, "\"");
		HtmlBuilder hb = HtmlBuilder.instance(viewPath);
		hb.setContext(context.getInternalUserContext());
		if(nodeCount > 2){
			String params = FuncStatic.trim(node.jjtGetChild(1).getFirstToken().image, "\"");
			hb.setValue( FuncStatic.urlParamsParse (params));
		}
		String content = hb.html();
		int num = content.indexOf("<content/>");
		
		writer.write(content.substring(0,num) ); 
 		node.jjtGetChild(nodeCount-1).render(context,writer);
 		writer.write(content.substring(num+10) );   
		return true;
	}

}
